package com.cloudcc.mobile.view.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.MenuToggleEvent;
import com.cloudcc.cloudframe.bus.StartWebEvent;
import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.util.DialogUtils;
import com.cloudcc.mobile.view.activity.BindActivity;
import com.cloudcc.mobile.weight.CustomProgressDialog;
import com.cloudcc.mobile.weight.webview.CloudccWebChromeClient;
import com.cloudcc.mobile.weight.webview.CloudccWebViewClient;

/**
 * @Description: webview基类
 * @author wangzhiqiang
 * @date 2015-12-4 上午9:03:05 webview id必须 是 webview
 * 
 */
public class BaseWebViewFragment extends BaseFragment {

	protected WebView mWebView;

	private WebSettings webSettings;

	protected CustomProgressDialog progressDialog;
	private boolean _isVisible;// 控制bindtoken影响的问题

	protected String mUrl = UrlManager.APP_UR;

	protected WebViewClient mWebViewClient;
	protected WebChromeClient mWebChromeClient;

	protected boolean isRedirected;

	@Override
	public void init() {
		super.init();
		mWebView = (WebView) findViewById(R.id.webview);
		onPreInitWebView();
		initSetting();
		initClient();
		initWebView();
	}

	/**
	 * 在初始化webview之前调用
	 */
	protected void onPreInitWebView() {

	}

	@SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
	protected void initSetting() {
		webSettings = mWebView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setAllowFileAccess(true);
		webSettings.setBlockNetworkImage(false);//后来加的
		webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);// 是否缓存
		webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
		webSettings.setSupportZoom(true);
		webSettings.setBuiltInZoomControls(false);// 不显示 放大图标
	}
	ValueCallback<Uri> mUploadMessage;
	/**
	 * 初始化 客户端
	 */
	protected int loadProgress =0;
	private final int OPEN_RESULT=1;
	private final int PINK_RESULT=2;
	protected void initClient() {
		mWebView.addJavascriptInterface(new JsInteration(), "cloudcc");
		mWebView.setWebViewClient(getWebViewClient());
		mWebView.setWebChromeClient(new CloudccWebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				loadProgress=newProgress;
				super.onProgressChanged(view, newProgress);
				if (loadProgress == 100) {
					stopProgressDialog();
				} else {
					startProgressDialog();
				}
			}
			
			
			public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {  
				if (mUploadMessage != null) return;
				mUploadMessage = uploadMsg;   
				Intent i = new Intent(Intent.ACTION_GET_CONTENT);
				i.addCategory(Intent.CATEGORY_OPENABLE);
				i.setType("*/*");
				startActivityForResult( Intent.createChooser( i, "选择文件" ), PINK_RESULT);
			}
		    public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType, String capture) {
				openFileChooser(uploadFile, acceptType);
			}
			// For Android < 3.0
			public void openFileChooser(ValueCallback<Uri> uploadMsg) {
				openFileChooser( uploadMsg, "" );
			} 
		});
	}
	@SuppressLint("SdCardPath")
	@Override
	public void onActivityResult(int requestCode, int resultCode, 
	        Intent intent) { 
		if(requestCode==PINK_RESULT)  {  
			if (null == mUploadMessage) return;  
			Uri result = intent == null || resultCode != Activity.RESULT_OK ? null  
					: intent.getData();  
			mUploadMessage.onReceiveValue(result);  
			mUploadMessage = null;  
		}
	}
	

	/**
	 * 初始化
	 */
	public void initWebView() {
		load();
	}

	public void load() {
		mWebView.loadUrl(mUrl);
		mWebView.reload();
	}

	/**
	 * 设置出事url
	 * 
	 * @return
	 */
	protected String getUrl() {
		return mUrl;
	}

	protected void setUrl(String url) {
		mUrl = url;
	}

	/**
	 * dialog开始显示
	 */
	protected void startProgressDialog() {
		if (_isVisible) {
			if (progressDialog == null) {
				progressDialog = CustomProgressDialog.createDialog(mContext);
				progressDialog.setCancelable(true);
				progressDialog.setCanceledOnTouchOutside(false);
			}
			if (!progressDialog.isShowing()) {
				try {
					progressDialog.show();
				} catch (Exception ex) {
					ex.printStackTrace();
				}
				
			}
		}
	}

	/**
	 * 停止dialog
	 */
	protected void stopProgressDialog() {
		if (_isVisible && progressDialog != null) {
			try {
				progressDialog.dismiss();
				progressDialog = null;
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	@Override
	public void onResume() {
		_isVisible = true;
		super.onResume();
	}
	@Override
	public void onPause() {
		_isVisible = false;
		super.onPause();
	}

	@Override
	public int getLayoutId() {
		return R.layout.widget_webview;
	}

	protected class BaseWebViewClient extends CloudccWebViewClient {

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			LogUtils.d("webview", "开始加载url:" + url);
			super.onPageStarted(view, url, favicon);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			LogUtils.d("webview", "开始完成url:" + url);
			super.onPageFinished(view, url);

		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			LogUtils.d("webview", "跳转url:" + url);
			if (UrlManager.isWapLogin(url)) {// 登录
				onLoginInvalid(view, url);
				return true;
			}
			if (UrlManager.isHome(url)) {// 主页
				getActivity().finish();
				return true;
			}
			return super.shouldOverrideUrlLoading(view, url);
		}

	}

	/**
	 * 失效的时候
	 * 
	 * @param view
	 * @param url
	 */
	public void onLoginInvalid(WebView view, String url) {
		EventEngine.register(this);
		Intent intent = new Intent(mContext, BindActivity.class);
		startActivity(intent);
	}

	/**
	 * 重新bin定的时候
	 * 
	 * @param event
	 */
	public void onEventMainThread(StartWebEvent event) {
		if (event.isError()) {
			EventEngine.post(new MenuToggleEvent(false, false));
			getActivity().finish();
			return;
		}
		mWebView.loadUrl(mUrl);
		EventEngine.uregister(this);
	}

	public class JsInteration {

		@JavascriptInterface
		public void back() {
			((Activity) mContext).finish();
		}

		@JavascriptInterface
		public void home() {
			DialogUtils.Exit(mContext);
		}

		@JavascriptInterface
		public void refresh() {
			mWebView.reload();
		}
	}

	public WebViewClient getWebViewClient() {
		return new BaseWebViewClient();
	}

}
